package com.example.user.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.user.mapper.SysUserMapper;
import com.example.user.po.SysUser;
import com.exmaple.cdc.service.SysMQService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.annotation.Resource;
import javax.transaction.UserTransaction;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/3/10 下午8:52
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private JtaTransactionManager jtaTransactionManager;

    @Resource
    private SysMQService sysMQService;

    /****
     * 注册用户信息
     * @param sysUser
     * @return
     */
    @Override
    public boolean registerUser1(SysUser sysUser) throws Exception {
        boolean flag = true;
        UserTransaction userTransaction = null;
        try {
            userTransaction = jtaTransactionManager.getUserTransaction();
            userTransaction.begin();
            sysUser.recalculateFields();
            this.save(sysUser);
            this.sysMQService.publish(sysUser.getClass().getName(), sysUser.getId(), "sys_user_register_message", sysUser.getUsername());
        } catch (Exception e) {
            flag = false;
            if (userTransaction != null) {
                userTransaction.rollback();
                userTransaction = null;
            }
        } finally {
            if (userTransaction != null) {
                userTransaction.commit();
            }
        }
        return flag;
    }


    /****
     * 数据插入
     * @param sysUser
     * @return
     * @throws Exception
     */
    @Override
    public SysUser registerUser2(SysUser sysUser) throws Exception {
        sysUser.recalculateFields();
        this.save(sysUser);
        this.sysMQService.publish(sysUser.getClass().getName(), sysUser.getId(), "sys_user_register_message", sysUser.getUsername());
        return sysUser;
    }
}
